package org.yxing.palpalgps.activity;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.yxing.palpalgps.AbstractActivity;
import org.yxing.palpalgps.BaseActivity;
import org.yxing.palpalgps.R;
import org.yxing.palpalgps.domain.AsyncImageLoader;
import org.yxing.palpalgps.domain.UserInfo;
import org.yxing.palpalgps.domain.AsyncImageLoader.ImageCallback;
import org.yxing.palpalgps.http.AsyncRequest;
import org.yxing.palpalgps.http.AsyncRequest.FetchListener;
import org.yxing.palpalgps.models.ListUserItem;
import org.yxing.palpalgps.oauth.OAuth;
import org.yxing.palpalgps.utils.Helper;
import org.yxing.palpalgps.widget.AsyncImageView;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class NearestUsersActivity extends BaseActivity implements ListView.OnItemClickListener{
    
    private static final String TAG = "NearestUsersActivity";
    
    private static final String URL_LIST_NEAREST = "list/nearest";
    private static final int SHOW_PROFILE = 1;
    
    /**
     * Interest id
     */
    private int iid;
    
    private int sid;
    
    private Adapter mAdapter;
    
    private ListView nearestListView;
    
    private AsyncImageLoader mAsyncImageLoader = new AsyncImageLoader();
    
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.nearest_users);
        setTitle("Nearest");
        
        Bundle bundle = getIntent().getExtras();
        iid = bundle.getInt("iid");
        sid = bundle.getInt("sid");
        
        nearestListView = (ListView) findViewById(R.id.nearest_users_listview);
        nearestListView.setOnItemClickListener(this);
        
        //adapter
        mAdapter = new Adapter();
        nearestListView.setAdapter(mAdapter);
        mAdapter.fetchData();
    }
    
    private class Adapter extends BaseAdapter {

        ArrayList<ListUserItem> data;
        
        private class ViewHolder {
        	public AsyncImageView imageView;
        }
        
        public Adapter() {
            data = new ArrayList<ListUserItem>();
        }
        
        public int getCount() {
            return data.size();
        }

        public ListUserItem getItem(int position) {
            return data.get(position);
        }

        public long getItemId(int position) {
            return getItem(position).getUid();
        }

        public View getView(int position, View convertView, ViewGroup parent) {
        	ViewHolder viewHolder = null;
            if (convertView == null) {
                convertView = getLayoutInflater().inflate(R.layout.nearest_users_list, null);
                viewHolder = new ViewHolder();
                viewHolder.imageView = (AsyncImageView) convertView.findViewById(R.id.face);
                convertView.setTag(viewHolder);
            } else {
            	viewHolder = (ViewHolder) convertView.getTag();
            }
            
            TextView nameView = (TextView) convertView.findViewById(R.id.name);
            TextView distance = (TextView) convertView.findViewById(R.id.distance);
            TextView genderView = (TextView) convertView.findViewById(R.id.gender);
            
            ListUserItem model = getItem(position);
        	nameView.setText(model.getName());
        	distance.setText(getString(R.string.distance) + ": " + model.getDistance() + " m");
        	String gender = model.getGender();
        	genderView.setText((gender.equals("m")) ? getString(R.string.male) : getString(R.string.female));
        	
        	String face = model.getPortrait();
        	
        	viewHolder.imageView.setDefaultResource(R.drawable.default_avatar);
        	if (!TextUtils.isEmpty(face)) {
        	    String url = Helper.getSmallPictureUrl(face);
        	    viewHolder.imageView.setUrl(url);
        	}
        	
            return convertView;
        }
        
        public void setItem(ListUserItem listUserItem) {
        	data.add(listUserItem);
        	notifyDataSetChanged();
        }
        
        public void fetchData() {
        	final List<BasicNameValuePair> params = OAuth.createAuthParams();
        	if (iid > 0)
        	    params.add(new BasicNameValuePair("iid", Integer.toString(iid)));
        	else if(sid > 0)
            	params.add(new BasicNameValuePair("sid", Integer.toString(iid)));
        	
        	AsyncRequest ar = new AsyncRequest(NearestUsersActivity.this);
        	ar.fetch(URL_LIST_NEAREST, params, new FetchListener() {
                
                public void onError(int code, String msg) {
                    
                }
                
                public void onComplete(JSONObject response) {
                    data.clear();
                    try {
                        JSONArray results = response.getJSONArray("result");
                        if (results.length() > 0) {
                            for (int i = 0; i < results.length(); i ++) {
                                try {
                                    JSONObject json = results.getJSONObject(i);
                                    ListUserItem listUserItem = new ListUserItem();
                                    listUserItem.setUid(json.getInt("uid"));
                                    listUserItem.setName(json.getString("name"));
                                    listUserItem.setDistance(json.getInt("distance"));
                                    listUserItem.setGender(json.getString("gender"));
                                    listUserItem.setPortrait(json.getString(UserInfo.KEY_FACE));
                                    listUserItem.setLastOnlineTimestamp(json.getInt("last_online"));
                                    setItem(listUserItem);
                                } catch (JSONException e) {
                                    Log.w(TAG, e.getMessage());
                                }
                            }
                        }
                        
                    } catch (JSONException e) {
                        Log.w(TAG, e.getMessage());
                    }
                }
            });
        }
    }

    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        Intent intent = new Intent(this, UserProfileActivity.class);
        intent.putExtra("uid", Long.toString(arg3));
        startActivityForResult(intent, SHOW_PROFILE);
    }
    
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
            case SHOW_PROFILE:
                if (data.getBooleanExtra(Helper.REFRESH, false)) {
                    mAdapter.fetchData();
                }
                break;
            }
        }
    }
}
